import { defineStore } from 'pinia';
import { ref } from 'vue';
import api from '@/http/api';

export const usePageCompStore = defineStore('pageComp', () => {
  const pageCompList = ref([]);
  const loading = ref(false);

  const setById = (id, data) => {
    if (!data) return;
    pageCompList.value[id] = data;
  };

  const getById = async(id, menuId) => {
    if (!id) return {};

    if (pageCompList.value[id]) {
      return pageCompList.value[id] || {};
    }

    if (loading.value) {
      await sleep(100);
      return await getById(id, menuId);
    }

    loading.value = true;
    try {
      const res = await api.post('/business/page-comp/' + (menuId ? (menuId + '/') : '') + id);
      loading.value = false;
      setById(id, res.data);
      return pageCompList.value[id] || {};
    } finally {
      loading.value = false;
    }
  };

  const sleep = async (d) => {
    return new Promise((resolve) => setTimeout(resolve, d))
  };

  const clearData = () => {
    pageCompList.value = [];
  };

  return { getById, clearData };
});
